package db_live

import (
	"context"
	"github.com/olivere/elastic/v7"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/common/api_models"
	"longmen/server/pkg/common/helper/const"
	"time"
)

type EsEntryExitStruct struct {
	LiveId    int64 `json:"live_id"`
	Uid       int   `json:"uid"`
	Duration  int64 `json:"duration"`
	IsSysUser uint8 `json:"is_system_user"`
	IoTimes   int   `json:"io_times"` //进出 次数
	Platform  int   `json:"platform"`
}

func WriteLiveRoomIoData(LiveId int64, exitStruct []*api_models.EntryExitStruct) error {
	bulk := global2.GetEs().Bulk()
	for _, v := range exitStruct {
		esEntryExitStruct := &EsEntryExitStruct{}
		duration := v.Duration
		if v.Duration < 1 && v.IOTimes < 2 { //如果只进一次直播间的，观看时间没有统计的
			duration = time.Now().Unix() - v.EntryTime
		}
		esEntryExitStruct.Uid = v.Uid
		esEntryExitStruct.Duration = duration
		esEntryExitStruct.IsSysUser = v.IsSysUser
		esEntryExitStruct.IoTimes = v.IOTimes
		esEntryExitStruct.LiveId = LiveId
		esEntryExitStruct.Platform = v.Platform
		//global2.Log.Debugf("esEntryExitStruct:%+v", esEntryExitStruct)
		req := elastic.NewBulkIndexRequest().
			Index(_const.ES_LiveRoom_Data). // 替换为你的索引名称
			Doc(esEntryExitStruct)
		bulk = bulk.Add(req)
	}

	// 执行批量写入
	_, err := bulk.Do(context.Background())
	//global.Log.Debugf("批量下入数据:%v,err:%v", response, err)
	if err != nil {
		global2.Log.Errorf("Error executing bulk request: %s\n", err)
		return err
	}
	return nil
}
